# Flask主应用入口
from flask import Flask, render_template, redirect, url_for, jsonify, request
from config import Config
from models import db
from services.reminder_service import reminder_service
from services.stats_service import stats_service

def create_app(config_class=Config):
    """应用工厂函数"""
    app = Flask(__name__)
    app.config.from_object(config_class)
    
    # 初始化数据库
    db.init_app(app)
    
    # 初始化提醒服务
    reminder_service.init_app(app)
    
    # 注册蓝图（路由）
    from routes.todo_routes import todo_bp
    from routes.password_routes import password_bp
    from routes.health_routes import health_bp
    from routes.goal_routes import goal_bp
    from routes.schedule_routes import schedule_bp
    
    app.register_blueprint(todo_bp)
    app.register_blueprint(password_bp)
    app.register_blueprint(health_bp)
    app.register_blueprint(goal_bp)
    app.register_blueprint(schedule_bp)
    
    # 首页路由
    @app.route('/')
    def index():
        """首页 - 显示统计仪表板"""
        return render_template('index.html')
    
    # 统计API
    @app.route('/api/dashboard-stats')
    def get_dashboard_stats():
        """获取仪表板统计数据"""
        stats = stats_service.get_dashboard_stats()
        return jsonify(stats)
    
    @app.route('/api/productivity-trends')
    def get_productivity_trends():
        """获取效率趋势"""
        days = int(request.args.get('days', 7))
        trends = stats_service.get_productivity_trends(days)
        return jsonify(trends)
    
    @app.route('/api/category-distribution')
    def get_category_distribution():
        """获取分类分布"""
        distribution = stats_service.get_category_distribution()
        return jsonify(distribution)
    
    # 创建数据库表
    with app.app_context():
        db.create_all()
    
    # 应用关闭时停止提醒服务
    @app.teardown_appcontext
    def shutdown_scheduler(exception=None):
        """应用关闭时清理"""
        pass  # 保持调度器运行
    
    return app

if __name__ == '__main__':
    app = create_app()
    app.run(debug=True, host='0.0.0.0', port=5000)

